package com.marco.system.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.marco.system.dao.FourLevelAdInfoDao;
import com.marco.system.domain.ChinaAdInfo;
import com.marco.system.domain.FourLevelAdInfo;
import com.marco.system.service.FourLevelAdInfoService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * FourLevelAdInfoServiceImpl.java
 * Create on 2017/4/18
 * Copyright(c) JD Inc 2017. All Rights Reserved.
 * <pre>
 * 功能说明：
 * </pre>
 */
@Service
@Transactional
public class FourLevelAdInfoServiceImpl implements FourLevelAdInfoService {
    private static final Logger logger = LoggerFactory.getLogger(FourLevelAdInfoServiceImpl.class);
    @Autowired
    private FourLevelAdInfoDao infoDao;

    @Override
    public void save(FourLevelAdInfo info) {
        try {
            infoDao.insert(info);
        } catch (Exception e) {
            throw new RuntimeException("保存四级地址出现异常", e);
        }
    }

    @Override
    public void updateLngAndLat(FourLevelAdInfo info) {
        try {
            infoDao.updateLngAndLat(info);
        } catch (Exception e) {
            throw new RuntimeException("更新四级地址出现异常", e);
        }
    }

    @Override
    public Map<String, List<FourLevelAdInfo>> getChinaForthLevelMap() {
        Map<String, List<FourLevelAdInfo>> chinaMaps = Maps.newHashMap();
        try {
            logger.info("正在构建中国四级地址人口库字典，请稍等");
            String parentKey = "0";
            List<FourLevelAdInfo> provinceList = infoDao.findByParentCode(parentKey);
            chinaMaps.put(parentKey, provinceList);
            for (FourLevelAdInfo province : provinceList) {
                parentKey = province.getCode();
                List<FourLevelAdInfo> cityList = infoDao.findByParentCode(parentKey);
                chinaMaps.put(parentKey, cityList);
                for (FourLevelAdInfo city : cityList) {
                    parentKey = city.getCode();
                    List<FourLevelAdInfo> countyList = infoDao.findByParentCode(parentKey);
                    chinaMaps.put(parentKey, countyList);
                    for (FourLevelAdInfo district : countyList) {
                        parentKey = district.getCode();
                        List<FourLevelAdInfo> townList = infoDao.findByParentCode(parentKey);
                        chinaMaps.put(parentKey, townList);
                    }
                }
            }
            logger.info("构建中国四级地址人口库字典完成!");
        } catch (Exception e) {
            throw new RuntimeException(" 构建中国四级地址人口库字典异常 ！", e);
        }
        return chinaMaps;
    }

    @Override
    public FourLevelAdInfo getInfoByLngAndLat(String lng, String lat) {
        List<FourLevelAdInfo> lists = infoDao.getInfoByLngAndLat(lng, lat);
        if (CollectionUtils.isEmpty(lists)) {
            return null;
        }
        Collections.sort(lists, new Comparator<FourLevelAdInfo>() {
            @Override
            public int compare(FourLevelAdInfo o1, FourLevelAdInfo o2) {
                return o1.getLevel() > o2.getLevel() ? 1 : -1;
            }
        });
        return lists.get(0);
    }

    @Override
    public FourLevelAdInfo getInfoByName(String province, String city, String district) {
        try {
            String key1 = province;
            if (province.length() > 2) {
                key1 = province.substring(0, 2);
            }
            String key2 = city;
            if (city.length() > 2) {
                key2 = city.substring(0, 2);
            }
            String key3 = district;
            if (district.length() > 2) {
                key3 = district.substring(0, 2);
            }

            List<FourLevelAdInfo> infoList = infoDao.getInfoByName(key1, key2, key3);
            if (CollectionUtils.isEmpty(infoList)) {
                return null;
            } else {
                if (infoList.size() != 1) {
                    for (FourLevelAdInfo info : infoList) {
                        if (info.getJdName().equals(district) || info.getShortName().equals(district)) {
                            return info;
                        }
                    }
                    logger.error("匹配CODE {} {} {} {}出现 {}中结果", infoList.get(0).getParentCode(), province, city,
                            district, infoList.size());
                }
                return infoList.get(0);
            }


        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public FourLevelAdInfo getInfoByNameAndParentCode(String shortName, String parentCode, final Double lng, final Double
            lat) {
        try {
            String key = shortName;
            if (StringUtils.isBlank(key)) {
                return null;
            }
            if (shortName.length() > 2) {
                key = shortName.substring(0, 2);
            }
            List<FourLevelAdInfo> list = infoDao.getInfoByNameAndParentCode(key, parentCode);
            Collections.sort(list, new Comparator<FourLevelAdInfo>() {
                @Override
                public int compare(FourLevelAdInfo o1, FourLevelAdInfo o2) {
                    Double p1 = Math.sqrt(Math.pow(o1.getLng() - lng, 2) + Math.pow(o1.getLat() - lat, 2));
                    Double p2 = Math.sqrt(Math.pow(o2.getLng() - lng, 2) + Math.pow(o2.getLat() - lat, 2));
                    return p1 > p2 ? 1 : -1;
                }
            });
            return list.get(0);
        } catch (Exception e) {
            return null;
        }
    }
}
